<template>
  <div>
    <div class="text-[12px] text-[#E50113] leading-[17px]">
      平台运输方式配置指，订单使用了此渠道，平台标发，用此配置物流商名称和承运商名称上传到对应平台进行标记发货。
    </div>
    <div v-for="(item, index) in platform" :key="item">
      <div class="text-[14px] text-[#333] leading-[20px] mb-[4px] mt-[16px]">
        {{ item.platform_name }}
      </div>
      <div
        class="flex items-center mb-[8px]"
        v-for="(i, ind) in item.data"
        :key="i.key"
      >
        <template
          v-if="getPlatformVal(i.platform_code, 'country') == 'country'"
        >
          <el-select
            v-model="i.country_code"
            filterable
            clearable
            placeholder="请选择国家"
            class="w-[180px] mr-[16px]"
          >
            <el-option
              v-for="item in country_data"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            >
            </el-option>
          </el-select>
        </template>
        <template v-if="i.country_codes?.length">
          <el-select
            v-model="i.country_code"
            filterable
            clearable
            @change="handleChangeCountry(i)"
            placeholder="请选择国家"
            class="w-[180px] mr-[16px]"
          >
            <el-option
              v-for="item in i.country_codes"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="i.carrier"
            clearable
            filterable
            placeholder="请选择承运人"
            class="w-[180px] mr-[16px]"
          >
            <el-option
              v-for="item in i.carrier_codes[i.country_code]"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            >
            </el-option>
          </el-select>
        </template>
        <template v-else>
          <el-select
            v-if="getPlatformVal(i.platform_code, 'type1')"
            v-model="i.carrier"
            filterable
            clearable
            @change="handleChange(i)"
            :placeholder="getPlatformVal(i.platform_code, 'type1')"
            class="w-[180px] mr-[16px]"
          >
            <el-option
              v-for="item in i.carrier_code"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            >
            </el-option>
          </el-select>
          <el-select
            v-if="
              getPlatformVal(i.platform_code, 'type2') &&
              getPlatformVal(i.platform_code, 'type2') != 'tracking Url'
            "
            v-model="i.delivery_service"
            clearable
            filterable
            :placeholder="getPlatformVal(i.platform_code, 'type2')"
            class="w-[180px] mr-[16px]"
          >
            <el-option
              v-for="item in i.delivery_service_code"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            >
            </el-option>
          </el-select>
          <el-input
            v-if="getPlatformVal(i.platform_code, 'type2') == 'tracking Url'"
            v-model="i.tracking_url"
            :placeholder="getPlatformVal(i.platform_code, 'type2')"
            class="mr-[16px]"
            style="width: 180px"
          />
        </template>

        <VGroup v-if="i.has_filter" class="mr-[16px]">
          <el-select
            v-model="i.filter_rule"
            class="w-[100px]"
            filterable
            placeholder="标发条件"
            clearable
          >
            <el-option
              v-for="item in [
                { label: '前缀', value: 1 },
                { label: '后缀', value: 2 },
                { label: '位数', value: 3 },
              ]"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            >
            </el-option>
          </el-select>
          <el-input v-model="i.filter_value" style="width: 180px" />
        </VGroup>
        <el-select
          v-model="i.shipment_type"
          class="w-[170px]"
          filterable
          placeholder="请选择发货追踪号"
          clearable
        >
          <el-option
            v-for="item in options['shipment_type']"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          >
          </el-option>
        </el-select>

        <!-- <el-checkbox
          v-model="i.is_apply"
          class="ml-[8px]"
          :true-label="1"
          :false-label="0"
        >
          是否适用此平台
        </el-checkbox> -->
        <el-checkbox
          v-model="i.has_filter"
          class="ml-[8px]"
          :true-label="1"
          :false-label="0"
          :disabled="item.data.length > 1&&!isCountryFlage(i)"
        >
          <!-- :disabled="item.data.length > 1&&!isCountryFlage(i)" -->
          根据前后缀判断标发
        </el-checkbox>
        <div class="ml-[8px]" v-if="isCountry(i)">
          <span
            class="hover:text-[#2080f0] cursor-pointer"
            @click="handleAdd(item, ind, index, i)"
            ><SvgIcon icon-class="Plus" class="text-[12px] inline" />
          </span>
          <span
            class="hover:text-[#2080f0] cursor-pointer ml-[4px]"
            @click="handleDelete(ind, index)"
            v-if="item?.data?.length > 1"
            ><SvgIcon icon-class="Minus" class="text-[12px] inline" />
          </span>
          <!-- <span
            class="hover:text-[#2080f0] cursor-pointer iconfont icon-add"
            @click.native="handleAdd(item, ind, index)"
          ></span>
          <span
            class="hover:text-[#2080f0] cursor-pointer iconfont icon-jian"
            @click="handleDelete(ind, index)"
            v-if="item?.data?.length > 1"
          ></span> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ElMessage } from "element-plus";
import { platformList, transformData } from "./data.js";
import { getPlatformOptions, carrier, deliveryService } from "@/api/public";
import { getCountry } from "@/api/index.js";
import { getLogisticsChannel, transportType } from "../../api";
const props = defineProps({
  data: { type: Object, default: () => ({}) },
  options: { type: Object, default: () => ({}) },
});

const platform = ref([]);
const originalPlatform = ref([]);
const flage = ref(false);

const groupByCode = (arr) => {
  return arr.reduce((acc, item) => {
    let existingGroup = acc.find(
      (group) => group.platform_code === item.platform_code
    );
    if (existingGroup) {
      existingGroup.data.push({ key: +new Date(), ...item });
    } else {
      acc.push({
        platform_code: item.platform_code,
        platform_name: item.platform_name,
        platform_id: item.platform_id,
        data: [{ key: +new Date(), ...item }],
      });
    }

    return acc;
  }, []);
};
const getPlatform = async () => {
  try {
    const { data } = await getPlatformOptions();
    let mergeResult = transformData(transportTypeList.value);
    for (let i = 0; i < data.length; i++) {
      let list =
        mergeResult.find(
          (item) => item.platform_code == data[i].platform_code
        ) || {};
      data[i].carrier_code = list?.carrier_code || [];
      data[i].delivery_service_code = list?.delivery_service || [];
      if (list?.country_code) {
        data[i].country_codes = list?.country_codes || [];
        data[i].carrier_codes = list?.carrier_codes || [];
      }
    }
    const codes = platformList.map((item) => item.code);
    // platform.value = data?.filter((obj) => codes?.includes(obj.platform_code));
    originalPlatform.value = data?.filter((obj) =>
      codes?.includes(obj.platform_code)
    );
    platform.value = groupByCode(originalPlatform.value);
    console.log(platform.value);
    flage.value = true;
  } catch (e) {
    console.error(e);
  }
};
const country_data = ref([]);
const getCountrylist = async () => {
  const { data } = await getCountry();
  country_data.value = data || [];
};
getCountrylist();
const transportTypeList = ref([]);
const getTransportType = async () => {
  try {
    const { data } = await transportType();
    transportTypeList.value = data || [];
    getPlatform();
  } catch (e) {
    console.error(e);
  }
};
getTransportType();
const getPlatformVal = (val, code) => {
  let data = platformList.find((i) => i.code == val);
  return data[code] ? data[code] : false;
};
const handleChange = (item) => {
  if (!item.shipment_type) {
    item.shipment_type = 2;
  }
};
const handleChangeCountry = (item) => {
  if (!item.shipment_type) {
    item.shipment_type = 2;
  }
  item.carrier = null;
};
watch(
  () => [props.data, flage.value],
  (val) => {
    if (!flage.value || !props?.data || !Array.isArray(props?.data)) return;
    const newPlatform = JSON.parse(JSON.stringify(platform.value));
    const _new = newPlatform?.map((n, ind) => {
      const _item = props.data?.filter((v) => v.platform_id === n.platform_id);
      const _original = originalPlatform.value.find(
        (i) => n.platform_id === i.platform_id
      );
      let data = [];
      if (_item?.length) {
        data = _item.map((item) => ({
          ..._original,
          ...item,
        }));
      } else {
        data = [{ ..._original }];
      }
      return {
        ...n,
        data,
        key: +new Date() + ind,
      };
    });
    platform.value = _new;
  }
);
const submit = () => {
  return new Promise((resolve, reject) => {
    try {
      // let _result = JSON.parse(JSON.stringify(platform.value));
      // let result = [];
      // _result.forEach((item) => {
      //   result = result.concat(item.data);
      // });
      // result = result.filter(
      //   (n) => !!n.logistics_id || !!n.carrier || !!n.shipment_type
      // );
      // result = result.map((n) => {
      //   return {
      //     id: n?.id || undefined,
      //     platform_id: n.platform_id,
      //     channel_id: n.channel_id,
      //     tracking_url: n.tracking_url,
      //     carrier: n.carrier,
      //     delivery_service: n.delivery_service,
      //     shipment_type: n.shipment_type,
      //     is_apply: n.is_apply,
      //     country_code: n.country_code,
      //     ext_json: null,
      //   };
      // });
      let result = platform.value
        .flatMap((item) => item.data)
        .filter((n) => n.logistics_id || n.carrier || n.shipment_type)
        .map((n) => ({
          id: n.id ?? undefined,
          platform_id: n.platform_id,
          channel_id: n.channel_id,
          tracking_url: n.tracking_url,
          carrier: n.carrier,
          delivery_service: n.delivery_service,
          shipment_type: n.shipment_type,
          has_filter: n.has_filter,
          country_code: n.country_code,
          filter_rule: n.filter_rule,
          filter_value: n.filter_value,
          ext_json: null,
        }));
      // if (!_result.length) {
      //   ElMessage.warning("请至少填写一条运输方式");
      //   reject();
      //   return;
      // }
      resolve(result);
    } catch (e) {
      ElMessage.warning(e || "请检查平台运输方式填写");
      reject("transportType");
    }
  });
};

const isCountry = (i) => {
  const country = getPlatformVal(i.platform_code, "country");
  const type1 = getPlatformVal(i.platform_code, "type1");
  return !!(i.has_filter || country === "country" || type1 === "请选择国家");
};
const isCountryFlage = (i) => {
  const country = getPlatformVal(i.platform_code, "country");
  const type1 = getPlatformVal(i.platform_code, "type1");
  return !!(country === "country" || type1 === "请选择国家");
};
const handleAdd = (data, ind, index, i) => {
  let target = originalPlatform.value.find(
    (item) => item.platform_id === data.platform_id
  );
  target.key = +new Date();
  target.has_filter = isCountryFlage(i) ? 0 : 1;
  platform.value[index].data.splice(
    ind + 1,
    0,
    JSON.parse(JSON.stringify(target))
  );
};
const handleDelete = (ind, index) => {
  platform.value[index].data.splice(ind, 1);
};
defineExpose({ submit });
</script>
